<?php

namespace app\admin\controller\stock;

use app\common\controller\Backend;
use Exception;
use think\Db;
use app\admin\model\UserDepart;
use fast\Tree;

/**
 * 股权证交易管理
 *
 * @icon fa fa-circle-o
 */
class Transfer extends Backend
{

    /**
     * Stock模型对象
     * @var \app\admin\model\StockTransfer
     */
    protected $model = null;
	protected $noNeedRight = ['depart'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\StockTransfer;

    }
	
	public function index()
	{
		$groupIds = $this->auth->getGroupIds();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$map = [];
			$type = intval($this->request->request('type'));
			if($groupIds[0] == 3)
			{
				if($type == 2)
				{
					$map['to_depart'] = $this->auth->depart_id;
					$map['status'] = ['in', [1,2]];
				}
				else
				{
					$map['from_depart'] = $this->auth->depart_id;
				}
			}

            $list = $this->model
					->where($where)
					->where($map)
                    ->order('status asc, id desc')
                    ->paginate($limit);

            foreach ($list as &$row) {
                $row['type'] = $type;
				$from_depart = UserDepart::get($row['from_depart']);
				$row['from_depart'] = $from_depart['name'];
				$to_depart = UserDepart::get($row['to_depart']);
				$row['to_depart'] = $to_depart['name'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

		$this->view->assign('groupid', $groupIds[0]);
		$this->assignconfig("admin", ['groupid' => $groupIds[0]]);
        return $this->view->fetch();
	}
	
	public function del($ids = "")
	{
		$ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					
					$sid = $v->sid;
					$row = model('stock')->get($sid);
					if ($row) {
						$row->status = 1;
						$row->save();
					}

                    $count += $v->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	public function accept($ids = "")
	{
		$ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					$v->status = 2;
					$v->accepttime = time();
					
					$stock = model('stock')->get(['uid'=>$v->to_uid]);
					if ($stock) {
						$stock->status = 1;
						$stock->save();
					}
					
                    $count += $v->save();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	public function review($ids = "")
	{
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (false === $this->request->isPost()) {
			$from_stock = model('stock')->get($row['sid']);
			$row['from_money'] = $from_stock['money'] - $row['money'];
			
			$to_user = model('User')->get($row['to_uid']);
			$to_stock = model('stock')->get(['uid'=>$to_user['id']]);
			if($to_stock)
			{
				$row['to_money'] = $to_stock['money'] + $row['money'];
			}
			else
			{
				$row['to_money'] = $row['money'];
			}
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
		
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
		
		$from_stock = model('stock')->get($row['sid']);
		if($from_stock['money']<$row['money'])
		{
			$this->error(__('装让金额不能大于本金'));
		}
		
        $result = false;
        Db::startTrans();
        try {
			if($from_stock['money']>$row['money'])
			{
				$new_from_stock = array(
					'uid' => $from_stock['uid'],
					'depart_id' => $from_stock['depart_id'],
					'uname' => $from_stock['uname'],
					'idcode' => trim($params['from_idcode']),
					'money' => $from_stock['money']-$row['money'],
					'lmoney' => trim($params['from_lmoney']),
					'releasetime' => time(),
					'status' => 1,
					'checktime' => time(),
					'createtime' => time(),
					'updatetime' => time()
				);
				
				db('stock')->insert($new_from_stock);
			}
			$from_stock->delete();
			
			$to_user = model('User')->get($row['to_uid']);
			$to_stock = model('stock')->get(['uid'=>$to_user['id']]);
			if($to_stock)
			{
				$new_to_stock = array(
					'uid' => $to_stock['uid'],
					'depart_id' => $to_stock['depart_id'],
					'uname' => $to_stock['uname'],
					'idcode' => trim($params['to_idcode']),
					'money' => $to_stock['money']+$row['money'],
					'lmoney' => trim($params['to_lmoney']),
					'releasetime' => time(),
					'status' => 0
				);
				$to_stock->delete();
			}
			else
			{
				$new_to_stock = array(
					'uid' => $to_user['id'],
					'depart_id' => $to_user['depart_id'],
					'uname' => $to_user['nickname'],
					'idcode' => trim($params['to_idcode']),
					'money' => $row['money'],
					'lmoney' => trim($params['to_lmoney']),
					'releasetime' => time(),
					'status' => 0
				);
			}
			model('stock')->allowField(true)->save($new_to_stock);
			
			$row->status = 1;
			$row->checktime = time();
			$result = $row->save();
            Db::commit();
        } catch (Exception $e) {
			Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('审核失败'));
        }
        $this->success('审核成功');
	}
	
	public function depart()
	{
		$groupList = collection(UserDepart::column('id,pid,name'))->toArray();

        Tree::instance()->init($groupList);
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $groupName = [];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
		
		echo json_encode($groupName);
		exit;
	}
}
